<?php
/**
 * 
 * 使用PHPMAILER的基本邮件发送器
 * 
 */
uses ( 'libs.vendors.mail.PHPMailer' );
class BaseMailSender implements IMailSender {
	private $mailer;
	public function __construct($options) {
		$options = array_merge ( array ('charset' => 'UTF-8', 'from' => '', 'fromname' => '', 'password' => '', 'port' => 25, 'secure' => '', 'auth' => true, 'host' => 'localhost' ), $options );
		@extract ( $options );
		$this->mailer->FromName = $fromname;
		$this->mailer = new PHPMailer ();
		$this->mailer->Username = $from;
		$this->mailer->Password = $password;
		$this->mailer->Port = $port;
		$this->mailer->IsSMTP ();
		$this->mailer->SMTPAuth = $auth;
		$this->mailer->CharSet = $charset;
		$this->mailer->SMTPSecure = $secure;
		$this->mailer->Host = $host;
	}
	/* (non-PHPdoc)
	 * @see IMailSender::AddAttachment()
	 */
	public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
		$this->mailer->AddAttachment ( $path, $name, $encoding, $type );
	}
	
	/* (non-PHPdoc)
	 * @see IMailSender::AddCC()
	 */
	public function AddCC($address, $name = '') {
		$this->mailer->AddCC ( $address, $name );
	}
	
	/* (non-PHPdoc)
	 * @see IMailSender::AddReplyTo()
	 */
	public function AddReplyTo($address, $name = '') {
		$this->mailer->AddReplyTo ( $address, $name );
	}
	
	/* (non-PHPdoc)
	 * @see IMailSender::sendHtml()
	 */
	public function sendHtml($subject, $to, $html, $altBody = '') {
		if (empty ( $to )) {
			return false;
		}
		$to = is_array ( $to ) ? $to : array ($to );
		$this->mailer->Subject = $subject;
		$this->mailer->IsHTML ( true );
		$this->mailer->Body = eregi_replace ( "[\]", '', $html );
		$this->mailer->AltBody = $altBody;
		foreach ( $to as $e => $n ) {
			if (is_numeric ( $e )) {
				$this->mailer->AddAddress ( $n );
			} else {
				$this->mailer->AddAddress ( $e, $n );
			}
		}
		$rst = $this->mailer->Send ();
		$this->mailer->ClearAllRecipients ();
		$this->mailer->ClearAttachments ();
		$this->mailer->ClearReplyTos ();
		return $rst;
	}
	
	/* (non-PHPdoc)
	 * @see IMailSender::sendText()
	 */
	public function sendText($subject, $to, $text, $altBody = '') {
		if (empty ( $to )) {
			return false;
		}
		$to = is_array ( $to ) ? $to : array ($to );
		$this->mailer->Subject = $subject;
		$this->mailer->IsHTML ( false );
		$this->mailer->Body = eregi_replace ( "[\]", '', $text );
		$this->mailer->AltBody = $altBody;
		foreach ( $to as $e => $n ) {
			if (is_numeric ( $e )) {
				$this->mailer->AddAddress ( $n );
			} else {
				$this->mailer->AddAddress ( $e, $n );
			}
		}
		$rst = $this->mailer->Send ();
		$this->mailer->ClearAllRecipients ();
		$this->mailer->ClearAttachments ();
		$this->mailer->ClearReplyTos ();
		return $rst;
	}
}